import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/product_gql.dart';
import 'package:labcloud_app/data/product.dart';

class ProductModel extends ChangeNotifier {

  List<Product>? _productList =  [];

  bool _isLoading = false;
  String? _errorMessage;

  List<Product>? get productList => _productList;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;

  /// 加载产品数据
  Future<void> loadProducts(BuildContext context, {int limit = 10}) async {
    if (_isLoading) return;
    
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final client = GraphQLProvider.of(context).value;
      
      final result = await client.query(
        QueryOptions(
          document: gql(ProductGQL.fetchProductList),
          variables: {
            'limit': limit,
          },
        ),
      );

      if (result.hasException) {
        _errorMessage = '加载产品失败: ${result.exception.toString()}';
      } else {
        // 解析GraphQL响应数据
        final productListData = result.data!['product']['productList'];
        final List<dynamic> productsData = productListData['products'];
        _productList = productsData.map((item) => Product.fromJson(item)).toList();
      }
    } catch (e) {
      _errorMessage = '加载产品失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 清除数据
  void clear() {
    _productList = null;
    _errorMessage = null;
    notifyListeners();
  }
}